package cn.itcast.service.system.impl;

import cn.itcast.dao.wxuser.WechartDao;
import cn.itcast.domain.wxLogin.WXUser;
import cn.itcast.service.system.WechartService;
import cn.itcast.utils.commons.HttpUtils;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

@Service
public class WechartServiceImpl implements WechartService {
    @Autowired
    private WechartDao wechartDao;

    private String appid = "wx3bdb1192c22883f3";
    private String secret = "db9d6b88821df403e5ff11742e799105";
    private String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private String wxInfoUrl = "https://api.weixin.qq.com/sns/userinfo";

    @Override
    public WXUser wxLogin(String code) {
        WXUser user = null;
        String atUtl = accessTokenUrl + "?code="+code+"&appid="+appid+"&secret="+secret+"&grant_type=authorization_code";
        Map<String,Object> map1= null;
        try {
            map1 = HttpUtils.sendGet(atUtl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Object access_token = map1.get("access_token");
        Object openid = map1.get("openid").toString();
        if (access_token == null && openid == null) {
            return user;
        }
       user = wechartDao.findByOpenid(openid.toString());
        if (user != null) {
            return user;

        } else {
            //如果用户不存在，获取微信用户信息
            String wxurl = wxInfoUrl + "?access_token=" + access_token + "&openid=" + openid;
            Map<String, Object> map2 = null;
            try {
                map2 = HttpUtils.sendGet(wxurl);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Object nickname = map2.get("nickname");
            Object headimgurl = map2.get("headimgurl");
            if (nickname == null || headimgurl == null) {
                return user;
            }
            //保存
            user = new WXUser();
            user.setOpenid(openid.toString());//openid
            user.setNickname(nickname.toString());//用户名
            user.setAvatar(headimgurl.toString());//用户头像



        }

        return user;
    }
}
